using Domain;
using ErrorCode;
using Infrastructure.Data;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System.Data;

namespace WriteAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class CustomerController : ControllerBase
    {
        private readonly ISqlSugarClient _db;

        public CustomerController(ISqlSugarClient db)
        {
            _db = db;
        }

        /// <summary>
        /// 创建客户
        /// </summary>
        [HttpPost("Create")]
        public async Task<APIResult<bool>> Create([FromBody] Customer customer)
        {
            try
            {
                // 生成客户编号
                customer.CustomerCode = await GenerateCustomerCode();
                customer.CreateTime = DateTime.Now;
                customer.AssignStatus = "pending"; // 新建客户默认为待分配状态

                // 保存客户信息
                var success = await _db.Insertable(customer).ExecuteCommandAsync() > 0;
                return success 
                    ? new APIResult<bool> { Code = APIEnum.OK, Msg = "创建成功", Data = true }
                    : new APIResult<bool> { Code = APIEnum.Error, Msg = "创建失败", Data = false };
            }
            catch (Exception ex)
            {
                return new APIResult<bool> { Code = APIEnum.Error, Msg = $"创建失败：{ex.Message}", Data = false };
            }
        }

        /// <summary>
        /// 删除客户
        /// </summary>
        [HttpPost("Delete")]
        public async Task<APIResult<bool>> Delete([FromBody] List<int> ids)
        {
            try
            {
                // 删除选中的客户记录
                var success = await _db.Deleteable<Customer>()
                    .Where(c => ids.Contains(c.Id))
                    .ExecuteCommandAsync() > 0;

                return success
                    ? new APIResult<bool> { Code = APIEnum.OK, Msg = "删除成功", Data = true }
                    : new APIResult<bool> { Code = APIEnum.Error, Msg = "删除失败", Data = false };
            }
            catch (Exception ex)
            {
                return new APIResult<bool> { Code = APIEnum.Error, Msg = $"删除失败：{ex.Message}", Data = false };
            }
        }

        /// <summary>
        /// 分配客户
        /// </summary>
        [HttpPost("Assign")]
        public async Task<APIResult<bool>> Assign(int id, string userName)
        {
            try
            {
                var success = await _db.Updateable<Customer>()
                    .SetColumns(it => new Customer
                    {
                        AssignStatus = "assigned",
                        UserName = userName,
                        AssignTime = DateTime.Now,
                        UpdateTime = DateTime.Now
                    })
                    .Where(it => it.Id == id)
                    .ExecuteCommandAsync() > 0;

                return success 
                    ? new APIResult<bool> { Code = APIEnum.OK, Msg = "分配成功", Data = true }
                    : new APIResult<bool> { Code = APIEnum.Error, Msg = "分配失败", Data = false };
            }
            catch (Exception ex)
            {
                return new APIResult<bool> { Code = APIEnum.Error, Msg = $"分配失败：{ex.Message}", Data = false };
            }
        }

        /// <summary>
        /// 生成客户编号
        /// </summary>
        private async Task<string> GenerateCustomerCode()
        {
            // 获取当天最后一个编号
            var today = DateTime.Now.ToString("yyyyMMdd");
            var lastCode = await _db.Queryable<Customer>()
                .Where(c => c.CustomerCode.StartsWith(today))
                .Select(c => c.CustomerCode)
                .FirstAsync();

            // 生成新编号
            if (string.IsNullOrEmpty(lastCode))
            {
                return $"{today}001";
            }
            else
            {
                var sequence = int.Parse(lastCode.Substring(8)) + 1;
                return $"{today}{sequence:D3}";
            }
        }

    }
}